// 碰撞检测模块
const { Events, World, Body } = Matter;
import { coins, enemies, platforms, score, getScore, setScore } from './gameObjects.js';

// 设置碰撞检测
function setupCollisions(engine, scoreElement) {
    // 使用外部score变量
    
    Events.on(engine, 'collisionStart', function (event) {
        const pairs = event.pairs;

        for (let i = 0; i < pairs.length; i++) {
            const pair = pairs[i];

            // 收集金币
            if ((pair.bodyA.label === 'mario' && pair.bodyB.label === 'coin') ||
                (pair.bodyA.label === 'coin' && pair.bodyB.label === 'mario')) {
                const coin = pair.bodyA.label === 'coin' ? pair.bodyA : pair.bodyB;
                World.remove(engine.world, coin);
                const tempCoins = coins.filter(c => c !== coin);
                coins.length = 0;
                coins.push(...tempCoins);

                setScore(getScore() + 10);
                scoreElement.textContent = `分数: ${getScore()}`;
            }

            // 碰到敌人
            if ((pair.bodyA.label === 'mario' && pair.bodyB.label === 'enemy') ||
                (pair.bodyA.label === 'enemy' && pair.bodyB.label === 'mario')) {
                const marioBody = pair.bodyA.label === 'mario' ? pair.bodyA : pair.bodyB;
                const enemy = pair.bodyA.label === 'enemy' ? pair.bodyA : pair.bodyB;

                // 判断马里奥是否在下落过程中（Y轴速度为正）
                if (marioBody.velocity.y > 0.5) {
                    // 消灭敌人
                    World.remove(engine.world, enemy);
                    const tempEnemies = enemies.filter(e => e !== enemy);
                    enemies.length = 0;
                    enemies.push(...tempEnemies);
                    // 给马里奥一个反弹力
                    Body.setVelocity(marioBody, { x: marioBody.velocity.x, y: -10 });
               
                    setScore(getScore() + 20);
                    scoreElement.textContent = `分数: ${getScore()}`;
                } else {
                    // 其他情况游戏结束
                    gameOver(document.getElementById('final-score'), document.getElementById('game-over'), getScore());
                }
            }

            // 破坏砖块
            if ((pair.bodyA.label === 'mario' && pair.bodyB.label === 'brick') ||
                (pair.bodyA.label === 'brick' && pair.bodyB.label === 'mario')) {
                const brick = pair.bodyA.label === 'brick' ? pair.bodyA : pair.bodyB;
                const marioBody = pair.bodyA.label === 'mario' ? pair.bodyA : pair.bodyB;

                // 只有从下方撞击才能破坏砖块
                if (marioBody.position.y > brick.position.y) {
                    World.remove(engine.world, brick);
                    const tempPlatforms = platforms.filter(p => p !== brick);
                    platforms.length = 0;
                    platforms.push(...tempPlatforms);
                    setScore(getScore() + 5);
                    scoreElement.textContent = `分数: ${getScore()}`;
                }
            }
        }
    });
    
    return { 
        getScore,
        updateScore: (value) => {
            // score = value;
            setScore(value);
            if (scoreElement) scoreElement.textContent = `分数: ${getScore()}`;
        }
    };
}

// 游戏结束处理
function gameOver(finalScoreElement, gameOverElement, score = 0) {
    if (!finalScoreElement || !gameOverElement) {
        console.error('游戏结束元素未定义');
        return true;
    }
    finalScoreElement.textContent = score;
    gameOverElement.style.display = 'block';
    return true;
}

export { setupCollisions, gameOver };